import { getToken, setToken, listToTree } from "@/utils/common";
import { getPersonAPI, getPermmenuAPI } from "@/api/user";

export default {
  namespaced: true,

  state: () => ({
    token: getToken(), // 用户token
    person: null,
    menus: [], // 用户菜单权限数据，包含菜单，路由，按钮
    perms: [], // 用户权限数据
    siderType: true
  }),

  getters: {
    menuTree(state) {
      const list = state.menus.filter((item) => item.type != 2 && item.isShow);
      return listToTree(list);

    },
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload;
      // 写入本地存储
      setToken(payload);
    },
    setPerson(state, payload) {
      state.person = payload;
    },
    setPermmenu(state, payload) {
      state.menus = payload.menus;
      state.perms = payload.perms;
    },
    changeSiderType(state) {
      state.siderType = !state.siderType;
    }
  },
  actions: {
    // 退出登录
    logout({ commit }) {
      commit("setToken", "");
    },
    // 优化下两个结合在一起
    get({ dispatch }) {
      dispatch("getPerson");
      dispatch("getPermmenu");
    },

    // 获取当前用户的个人信息
    getPerson({ commit }) {
      // 调用接口
      getPersonAPI().then((result) => {
        // console.log('result', result);
        commit("setPerson", result);
      });
    },
    getPermmenu({ commit }) {
      getPermmenuAPI().then((result) => {
        // console.log("result", result);
        commit("setPermmenu", result);
      });
    },
  },
};
